# 视图集和扩展类
from rest_framework.mixins import ListModelMixin
from rest_framework.viewsets import ModelViewSet, GenericViewSet

# 数据库模型
from .models import Users, Roles, Menus, Rights, Categories
# Create your views here.

# 序列化器
from .serializers import UserSerializer, RolesSerializer, UpdateUserSerializer, MenuSerializer, RightSerializer, \
    RightsSerializer, CategoriesSerializer

# 分页
from utils.pagination import MyPagination

# 排序
from rest_framework.filters import OrderingFilter, SearchFilter

# 过滤
from django_filters.rest_framework import DjangoFilterBackend

# 自定义排序类
from utils.order_filters import UsersFilter


# 角色
class RolesView(ModelViewSet):
    queryset = Roles.objects.all()
    serializer_class = RolesSerializer


# 用户
class UsersView(ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UserSerializer
    pagination_class = MyPagination
    # drf搜索，search为关键字对用户名和email进行查询，用户名和邮箱是与的关系
    filter_backends = [SearchFilter, OrderingFilter]
    search_fields = ('username', 'email')
    ordering_fields = ('id', 'create_time')
    # 可以放在setting中设置全局，也可以放在视图或视图集中设置局部
    # 配置上OrderingFilter之后，所有字段可作排序，可以通过ordering_fields来限制
    # filter_backends = [DjangoFilterBackend]
    # 精确查找，可以通过email和邮箱作为关键字查找，可以只通过用户名查找，也可以同时通过用户名
    # 和邮箱查找，邮箱和用户名的关系是 and，有一项不符合就查找不到
    # filterset_fields = ['username', 'email']

    # 根据筛选类进行模糊查询，可查询用户名和邮箱,两者为与的关系，也可以只匹配任意一项
    # filterset_class = UsersFilter


    def get_serializer_class(self):
        if self.action == 'update' or self.action == 'partial_update':
            return UpdateUserSerializer
        else:
            return UserSerializer

    def get_queryset(self):
        if self.request.data.get('query') is not None:
            return Users.objects.filter(email__icontains=self.request.data['query'])
        return self.queryset

    # def filter_queryset(self, queryset):


# 菜单栏展示
class MenuView(GenericViewSet, ListModelMixin):
    queryset = Menus.objects.filter(parent_id=None)
    serializer_class = MenuSerializer


# 权限展示
class RightsView(GenericViewSet, ListModelMixin):
    queryset = Rights.objects.all()
    serializer_class = RightsSerializer


# 展示树状图
class CategoriesView(ModelViewSet):
    queryset = Categories.objects.filter(cat_pid=None)
    serializer_class = CategoriesSerializer
    pagination_class = MyPagination

    def get_queryset(self):
        if len(self.request.query_params) <= 0:
            self.pagination_class = None
        else:
            self.pagination_class = MyPagination
        return self.queryset


# 增删改查
class CategoriesViews(ModelViewSet):
    queryset = Categories.objects.all()
    serializer_class = CategoriesSerializer
